<?php

namespace addons\xcrontab\library;

use Exception;

class RunStatus
{
    const ADDON_NAME = 'xcrontab';

    public static $pidFile = RUNTIME_PATH . 'addons/xcrontab/pid.txt';

    public static function clean()
    {
        static::deletepidFile();
    }

    public static function initPid()
    {
        $dir = dirname(static::$pidFile);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        if (!is_file(static::$pidFile)) {
            @touch(static::$pidFile);
        }
    }

    public static function lockStatus()
    {
        static::initPid();
        $handle = fopen(static::$pidFile, 'w');
        if (flock($handle, LOCK_SH | LOCK_NB)) {
            fseek($handle, 0);
            fwrite($handle, time());
            fflush($handle);
            flock($handle, LOCK_UN);
            fclose($handle);
            return true;
        }
        return null;
    }

    public static function unlockStatus($handle)
    {
        return flock($handle, LOCK_UN);
    }


    public static function everyminuteTimer()
    {
        $sec = date('s');
        $sleepsec = 60 - $sec;
        if ($sleepsec) {
            sleep($sleepsec);
        } else {
            sleep(60);
        }
        // while (true) {
        //     $sec = date('s');
        //     if (intval($sec) == 0) {
        //         break;
        //     }
        // }
        return true;
    }

    /**
     * 重写读取信息，主要框架自带有缓存，必须实时知道配置
     *
     * @return void
     */
    public static function getAddonInfo()
    {
        return parse_ini_file(ADDON_PATH . static::ADDON_NAME . '/info.ini');
    }

    /**
     * 重写读取配置，主要框架自带有缓存，必须实时知道配置
     *
     * @return array
     */
    public static function getAddonConfig()
    {
        //不能使用 get_addon_config 有缓存
        //当定时器轮询的时候，必须重写读取配置，检查配置想的修改
        $config = require ADDON_PATH . static::ADDON_NAME . '/config.php';
        $data = [];
        foreach ($config as $param) {
            $data[$param['name']] = $param['value'];
        }
        return $data;
    }

    public static function isActive()
    {
        $config = self::getAddonConfig();
        return isset($config['active']) ? $config['active'] : 0;
    }

    /**
     * 是否可执行
     * 如果为空，或者多少分钟没有更新时间戳了，则认定停止运行了，可以重新运行了
     *  配置执行超时时间秒
     *
     * @param number $timeout
     * @return void
     */
    public static function enableExecuteScript($timeout)
    {
        if (file_exists(self::$pidFile)) {
            return false;
        }
        return true;
    }

    public static function lastRunTime()
    {
        if (file_exists(static::$pidFile)) {
            return intval(file_get_contents(static::$pidFile));
        }
        return 0;
    }

    public static function deletepidFile()
    {
        @unlink(static::$pidFile);
    }

    public static function updateStatus()
    {
        file_put_contents(self::$pidFile, time());
    }

    public static function overmaxdays($starttime)
    {
        $config = self::getAddonConfig();
        if (((time() - $starttime) / 3600 / 24) >= intval($config['maxdays'])) {
            return true;
        } else {
            return false;
        }
    }

    public static function dblost(Exception $e)
    {

        $info = [
            'server has gone away',
            'no connection to the server',
            'Lost connection',
            'is dead or not enabled',
            'Error while sending',
            'decryption failed or bad record mac',
            'server closed the connection unexpectedly',
            'SSL connection has been closed unexpectedly',
            'Error writing data to the connection',
            'Resource deadlock avoided',
            'failed with errno',
        ];

        $error = $e->getMessage();

        foreach ($info as $msg) {
            if (false !== stripos($error, $msg)) {
                return true;
            }
        }
        return false;
    }
}
